package com.totoro.rabbitmq.ps;

import com.rabbitmq.client.*;
import com.totoro.rabbitmq.RabbitMQUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 发布订阅客户端。每个客户端通过订阅服务端的Exchange 和Routing 来获取服务端的消息。
 * 每个客户端的queue都不同，将这个queue绑定到服务端的Exchange和routingkey上
 * Created by Niki on 2018/3/30 8:35
 */
public class PSClient {
    private static final String EXCHANGE_NAME = "ps_exchange_demo";
    private static final String ROUTING_KEY = "ps_routing_demo";
    private static ConnectionFactory connectionFactory = RabbitMQUtil.getConnectionFactory();

    private static void receiveMsg(final String name) {
        connectionFactory = RabbitMQUtil.getConnectionFactory();
        try {
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();

            //产生一个随机queue。
            String queue = channel.queueDeclare().getQueue();
            //将queue绑定到exchange和routing上。类似于订阅服务端的消息
            channel.queueBind(queue, EXCHANGE_NAME, ROUTING_KEY);

            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);
                    System.out.println("订阅客户" + name + "收到消息：" + new String(body, "utf-8"));
                }
            };

            channel.basicConsume(queue, true, consumer);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        receiveMsg("1");
        receiveMsg("2");
    }
}
